package com.mhkj.base.itemInfo.item.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.mhkj.base.itemInfo.item.dao.ItemDao;
import com.mhkj.base.itemInfo.item.entity.Item;
import com.mhkj.base.itemInfo.item.service.ItemService;
import com.mhkj.base.rbac.role.entity.SystemRole;
import com.mhkj.base.rbac.role.service.MyRoleService;
import com.mhkj.common.util.ItemHelper;
import com.mics.core.common.componet.Pagination;
import com.mics.core.system.base.service.impl.BaseServiceImpl;
import com.mics.core.system.rbac.service.DictionaryService;

@Service
public class ItemServiceImpl extends BaseServiceImpl<Item> implements ItemService {
	@Resource
	private ItemDao itemDao;
	@Resource
	private DictionaryService dictionaryService;
	@Resource
	private MyRoleService myRoleService;
	@Resource
	private ItemHelper itemHelper;
	@Resource
	public void setItemDao(ItemDao itemDao) {
		super.setBaseRepository(itemDao);
	}

	@Override
	public Pagination<Item> listByPage(Item item, int pageIndex, int size ) {
		Specification<Item> spec = new Specification<Item>() {
			/**
			 * 序列号
			 */
			private static final long serialVersionUID = -786003485941679959L;

			@Override
			public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> lstPredicates = new ArrayList<Predicate>();
				Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
				
				
				 Join<Object, Object> tSysNation = root.join("tSysNation",JoinType.INNER);

				if (!StringUtils.isEmpty(item.getCityId())) {
					lstPredicates.add(criteriaBuilder.equal(tSysNation.get("id"),item.getCityId()));
				}
				
				if (!StringUtils.isEmpty(item.getProvinceId())) {
					lstPredicates.add(criteriaBuilder.equal(tSysNation.get("parentId"),item.getProvinceId()));
				}
				
				if (!StringUtils.isEmpty(item.getName())) {
					lstPredicates.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + item.getName() + "%"));
				}
				 
				if (!StringUtils.isEmpty(item.getAffiliatedCompanyId())) {
					lstPredicates.add(criteriaBuilder.equal(root.get("affiliatedCompanyId").as(String.class), item.getAffiliatedCompanyId()));
				}
				
			 
				return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
			}
		};
		Page<Item> pageT = itemDao.findAll(spec, PageRequest.of(pageIndex, size, Sort.Direction.DESC, "createDate"));
		Pagination<Item> pagination = new Pagination<Item>();
		pagination.setTotal(itemDao.count(spec));
		pagination.setData(pageT.getContent());
		return pagination;
	}

	@Override
	public List<Item> getProvinceWithItem() {
		return   itemDao.getProvinceWithItem();
	}
	/**
	 * 获取已经建立项目对应的省下城市
	 */
	@Override
	public List<Item> getCityWithProvince(Long provinceId) {
		return itemDao.getCityWithProvince(provinceId);
	}

	@Override
	public String del(Item t) {
		return super.del(t);
	}

	@Override
	public List<Item> getListItemByaffiliatedCompanyId(String CompanyId,String itemName, Integer status){
		// TODO Auto-generated method stub
		Specification<Item> spec = new Specification<Item>() {
			/**
			 * 序列号
			 */
			private static final long serialVersionUID = -167007863315756825L;

			@Override
			public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> lstPredicates = new ArrayList<Predicate>();
				Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
				
				
				 
				if (!StringUtils.isEmpty(CompanyId)) {
					lstPredicates.add(criteriaBuilder.equal(root.get("affiliatedCompanyId"),CompanyId));
				}
				
				if (!StringUtils.isEmpty(itemName)) {
					lstPredicates.add(criteriaBuilder.like(root.get("name").as(String.class), "%" +itemName+ "%"));
				}
				 
				if (!StringUtils.isEmpty(status)) {
					lstPredicates.add(criteriaBuilder.equal(root.get("statis").as(Integer.class), status));
				}
	              if(itemHelper.getCurrentUserItems().size() > 0 ){
	  					Predicate p3=criteriaBuilder.and(root.in(itemHelper.getCurrentUserItems()));
	  		            lstPredicates.add(p3);
	                  }else{
	  					Predicate p3=criteriaBuilder.and(root.isNull());
	  		            lstPredicates.add(p3);
	                  }
				return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
			}
		};
		
		List<Item> findAll = itemDao.findAll(spec);
		
		return findAll;
	}

	@Override
	public List<Item> getItemWithCityId(Long provinceId,Long cityId) {
		// TODO Auto-generated method stub
		
		if(StringUtils.isEmpty(cityId)) {
			
			return itemDao.getItemWithProvinceId(provinceId);
		}else {
			return itemDao.getItemWithCityId(cityId);
		}
		
	}

	 
	@Override
	public List<Item> getListItem(String CompanyId,String itemName, Integer status,Long cityId,  Long provinceId){
		// TODO Auto-generated method stub
		Specification<Item> spec = new Specification<Item>() {
			/**
			 * 序列号
			 */
			private static final long serialVersionUID = -167007863315756825L;

			@Override
			public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> lstPredicates = new ArrayList<Predicate>();
				Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
				
				
				 Join<Object, Object> tSysNation = root.join("tSysNation",JoinType.INNER);

					if (!StringUtils.isEmpty(cityId)) {
						lstPredicates.add(criteriaBuilder.equal(tSysNation.get("id"),cityId));
					}
					
				
				if (!StringUtils.isEmpty(CompanyId)) {
					lstPredicates.add(criteriaBuilder.equal(root.get("affiliatedCompanyId"),CompanyId));
				}
				
				if (!StringUtils.isEmpty(itemName)) {
					lstPredicates.add(criteriaBuilder.like(root.get("name").as(String.class), "%" +itemName+ "%"));
				}
				 
				if (!StringUtils.isEmpty(status)) {
					lstPredicates.add(criteriaBuilder.equal(root.get("statis").as(Integer.class), status));
				}
				
				if (!StringUtils.isEmpty(provinceId)) {
					lstPredicates.add(criteriaBuilder.equal(tSysNation.get("parentId").as(Integer.class), provinceId));
				}
				
			 
				return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
			}
		};
		
		List<Item> findAll = itemDao.findAll(spec);
		
		return findAll;
	}

	@Override
	public List<Item> checkItemName(String affiliatedCompanyId, String name) {
		Specification<Item> spec = new Specification<Item>() {
			/**
			 * 序列号
			 */
			private static final long serialVersionUID = -167007863315756825L;
			@Override
			public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> lstPredicates = new ArrayList<Predicate>();
				Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
				if (!StringUtils.isEmpty(affiliatedCompanyId)) {
					lstPredicates.add(criteriaBuilder.equal(root.get("affiliatedCompanyId"),affiliatedCompanyId));
				}
				if (!StringUtils.isEmpty(name)) {
					lstPredicates.add(criteriaBuilder.equal(root.get("name").as(String.class), name));
				}
				return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
			}
		};
		List<Item> findAll = itemDao.findAll(spec);
		return findAll;
	}

	@Override
	@Transactional
	public void grantRole(Item item, String roleIds) {
		Item itemTemp = getById(item.getId());
		String[] roleIdsTemp = roleIds.split(",");
		List<SystemRole> systemRoles = new ArrayList<SystemRole>();
		for(String rid:roleIdsTemp){
			if(StringUtils.hasText(rid)){
				SystemRole systemRole = myRoleService.getById(Long.valueOf(rid));
				systemRoles.add(systemRole);
			}
		}
		itemTemp.setSystemRoles(systemRoles);
		edit(itemTemp);		
	}



}
